package org.example.analysis.util;

import com.github.javaparser.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * Java符号解析工具类
 */
@Slf4j
public class JavaSymbolResolver {
    private final CombinedTypeSolver combinedTypeSolver;
    private String sourceDir;
    private JavaSymbolSolver symbolSolver;
    
    public JavaSymbolResolver() {
        this.combinedTypeSolver = new CombinedTypeSolver();
        // 添加反射类型解析器，用于解析JDK和依赖库中的类型
        this.combinedTypeSolver.add(new ReflectionTypeSolver());
        this.symbolSolver = new JavaSymbolSolver(combinedTypeSolver);
    }
    
    /**
     * 设置源代码目录
     *
     * @param sourceDir 源代码目录路径
     */
    public void setSourceDir(String sourceDir) {
        if (this.sourceDir != null && this.sourceDir.equals(sourceDir)) {
            return;
        }
        
        this.sourceDir = sourceDir;
        
        // 移除旧的源代码解析器并添加新的
        try {
            combinedTypeSolver.add(new JavaParserTypeSolver(new File(sourceDir)));
            // 重新创建符号解析器
            this.symbolSolver = new JavaSymbolSolver(combinedTypeSolver);
            log.info("成功设置源代码目录: {}", sourceDir);
        } catch (Exception e) {
            log.error("设置源代码目录失败: {}", sourceDir, e);
        }
    }
    
    /**
     * 获取类型解析器
     */
    public TypeSolver getTypeSolver() {
        return combinedTypeSolver;
    }
    
    /**
     * 获取符号解析器
     */
    public JavaSymbolSolver getSymbolSolver() {
        return symbolSolver;
    }
} 